<template>
  <div class="app-multiple-image-upload" :style="{height: `${108 + (size ? 26 : 0)}px`}">
    <span class="el-upload__tip" v-if="size">建议尺寸：{{size}}像素</span>
    <el-upload list-type="picture-card"
               :action="url"
               :http-request="upload"
               :on-success="onSuccess"
               :on-remove="onRemove"
               :show-file-list="true"
               :file-list="fileList"
               :disabled="disabled"
               name="multipartFile">
      <i class="el-icon-plus"></i>
    </el-upload>
  </div>
</template>

<script>
  import axios from 'axios'
  import qs from 'query-string'

  export default {
    props: {
      value: Array,
      urlProp: String,
      size: String,
      disabled: {type: Boolean, default: false}
    },

    data() {
      return {
        url: `${process.env.API_URL_BASE}/commons/attachments/uploadTmp.do`
      }
    },

    computed: {
      fileList() {
        return (this.value || [])
          .map(x => this.urlProp ? x[this.urlProp] : x)
          .map(filename => ({url: this.imageUrl(filename)}));
      }
    },

    methods: {
      imageUrl(filename) {
        return `${process.env.API_URL_BASE}/commons/attachments/download.do?filename=${filename}`;
      },

      filename(url) {
        return qs.parse(new URL(url).search).filename;
      },

      upload({action, filename, file, onSuccess}) {
        const form = new FormData();
        form.append(filename, file);
        axios.post(action, form).then(onSuccess)
      },

      onSuccess(resp) {
        this.$emit('input', [
          ...(this.value || []),
          this.urlProp ? {[this.urlProp]: resp.data.data} : resp.data.data
        ]);
      },

      onRemove(file, fileList) {
        this.$emit('input',
          _(fileList)
            .tap(x => console.log(x))
            .map(f => this.filename(f.url))
            .tap(x => console.log(x))
            .map(url => this.urlProp ? {[this.urlProp]: url} : url)
            .tap(x => console.log(x))
            .value()
        );
      }
    }
  }
</script>

<style lang="scss">
  .app-multiple-image-upload{
    .el-upload--picture-card{
      width:100px!important;
      height:100px!important;
      position: relative!important;
    }
    .el-upload-list--picture-card .el-upload-list__item{
      width:100px!important;
      height:100px!important;
      position: relative!important;
    }
    .el-upload--picture-card i{
      position: absolute!important;
      left:35%!important;
      line-height: 100px!important;
    }
  }


</style>
